<script setup lang="ts">
import { onUnmounted, reactive } from "vue";

defineOptions({ name: "WebxBtnCode" });
const emits = defineEmits(["getCode"]);
const props = defineProps({
  // 默认文本
  text: { type: String, default: "获取验证码" },
  // 倒计时
  time: { type: Number, default: 60 }
});

const codeBtnData = reactive({
  // 按钮内显示的文字
  btnText: props.text,
  // 按钮倒计时剩余
  surplusTime: props.time,
  // 定时器
  timer: null as any,
  // 设置按钮倒计时文字
  onSetBtnText() {
    codeBtnData.surplusTime--;
    codeBtnData.btnText = `${codeBtnData.surplusTime}秒后重新${props.text}`;
  },
  // 按钮重置
  onReset() {
    if (codeBtnData.timer) {
      clearTimeout(codeBtnData.timer);
    }
    codeBtnData.timer = null;
    codeBtnData.btnText = props.text;
    codeBtnData.surplusTime = props.time;
  },
  // 开始倒计时
  onStart() {
    if (codeBtnData.timer) return;
    emits("getCode");
    codeBtnData.onSetBtnText();
    codeBtnData.timer = setInterval(() => {
      codeBtnData.onSetBtnText();
      if (codeBtnData.surplusTime < 1) {
        codeBtnData.onReset();
      }
    }, 1000);
  }
});

onUnmounted(() => {
  // 关闭倒计时
  codeBtnData.onReset();
});
</script>

<template>
  <AButton class="flex-shrink-0" :disabled="!!codeBtnData.timer" @click="codeBtnData.onStart">
    {{ codeBtnData.btnText }}
  </AButton>
</template>

<style scoped lang="less"></style>
